package yanc.app

import org.apache.http.Consts
import org.apache.http.HttpStatus
import org.apache.http.NameValuePair
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.impl.client.HttpClients
import org.apache.http.message.BasicNameValuePair

class HTTPUtil {
    public static boolean post(String url, Map<String, String> params) {
        def httpclient = HttpClients.createDefault()
        def httpPost = new HttpPost(url)
        // 参数处理
        if (params != null && !params.isEmpty()) {
            def list = new ArrayList<NameValuePair>()

            def it = params.entrySet().iterator()
            while (it.hasNext()) {
                def entry = it.next()
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()))
            }

            httpPost.setEntity(new UrlEncodedFormEntity(list, Consts.UTF_8))
        }
        // 执行请求
        try {
            def response = httpclient.execute(httpPost)
            response.getStatusLine().getStatusCode()
        } catch (Exception e) {
            e.printStackTrace()
        }
        return true
    }
    /**
     * 校验token, 如果正确返回username
     * @param url
     * @param token
     * @return
     */
    public static String verifyToken(String url, String token) {
        def httpclient = HttpClients.createDefault()
        def httpGet = new HttpGet("${url}?token=${token}")
        // 执行请求
        try {
            def response = httpclient.execute(httpGet)
            def status = response.getStatusLine().getStatusCode()
            println("status: ${status}")
            if (status == HttpStatus.SC_OK) {
                def entity = response.getEntity()
                def input = entity.getContent()
                def br = new BufferedReader(new InputStreamReader(input))
                def str = br.readLine()
                def username = new String(str.getBytes("gbk"), "utf-8")
                println("username: ${username}")
                return username
            } else {
                return ""
            }

        } catch (Exception e) {
            return ""
        }
    }

    public static boolean invalidSession(String url, String token) {
        def httpclient = HttpClients.createDefault()
        def httpGet = new HttpGet("${url}?token=${token}")
        // 执行请求
        try {
            def response = httpclient.execute(httpGet)
            def status = response.getStatusLine().getStatusCode()
            println("status: ${status}")
            if (status == HttpStatus.SC_OK) {
                return true
            } else {
                return false
            }

        } catch (Exception e) {
            return false
        }
    }
}
